package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 移动端拦截器
 */
@Slf4j
@Component
public class MobileInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenProperties jwtTokenProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1.获取请求头
        String jwt = request.getHeader("Authorization");
        if(StrUtil.isBlank(jwt)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //        2.解析jwt
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), jwt);



        Long userId = Long.valueOf(claims.get("id").toString());
        if(ObjectUtil.isEmpty(userId)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        ThreadLocalUtil.set(userId);


        return true; // 放行
    }

}